<template>
  <!--定时任务管理-->
  <el-row style="height:100%">
    <page>
      <pageheader :event="'taskAdd'" :isShow="true">
        定时任务管理
      </pageheader>
      <div class="page-content">
        <el-card class="box-card tag-card">
          <el-row>
            <span>搜索：</span>
            <el-input v-model="keywords" size="small" clearable placeholder="请输入关键字" style="width:300px;">
              <el-button @click="deviceSearch" slot="append" icon="el-icon-search"></el-button>
            </el-input>
            <span style="margin-left: 20px">状态：</span>
            <el-select v-model="status" @change="isChangeType"
                       size="small" style="width:200px">
              <el-option label="全部" value='-1'></el-option>
              <el-option label="启用" value='1'></el-option>
              <el-option label="暂停" value='2'></el-option>
              <el-option label="未启用" value='0'></el-option>
            </el-select>
          </el-row>
          <el-table :data="dataTable" size="small" stripe>
            <el-table-column label="序号" type="index" :index="indexMethod" align="center" width="60"></el-table-column>
            <el-table-column label="企业名称" prop="company_name" align="center"></el-table-column>
            <el-table-column label="任务描述" prop="task_desc" align="center"></el-table-column>
            <el-table-column label="任务定时表达式" prop="cron" align="center"></el-table-column>
            <el-table-column label="获取多长时间的数据" prop="data_intervals" align="center"></el-table-column>
            <el-table-column label="当前时间往前推算多长时间" prop="push_forward_time" align="center"></el-table-column>
            <el-table-column label="数据分包条数" prop="data_sum" align="center"></el-table-column>
            <el-table-column label="服务.方法名称" prop="bean_name"  align="center" width="100">
              <template slot-scope="scope">
                <span>{{scope.row.bean_name}}.{{scope.row.method_name}}</span>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="created_time" align="center" width="110px" fixed="right"></el-table-column>
            <el-table-column label="更新时间" prop="updated_time" align="center" width="110px" fixed="right"></el-table-column>
            <el-table-column label="状态" prop="status" align="center" width="80px" fixed="right">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status == 1" type="success" size="small">启用</el-tag>
                <el-tag v-else-if="scope.row.status == 2" type="info" size="small">暂停</el-tag>
                <el-tag v-else size="mini">未启用</el-tag>
              </template>
            </el-table-column >
            <el-table-column label="状态修改" prop="status" align="center" width="170px" fixed="right">
              <template slot-scope="scope">
                <el-button v-if="scope.row.status == 0" @click="taskChange(scope.row.id,1)" type="primary" size="mini">启用</el-button>
                <el-button v-if="scope.row.status != 0 && scope.row.status == 1"
                           @click="taskChange(scope.row.id,2)" size="small" type="info">暂停</el-button>
                <el-button v-if="scope.row.status != 0 && scope.row.status == 2"
                           @click="taskChange(scope.row.id,1)" size="small" type="success">启动</el-button>
                <el-button v-if="scope.row.status != 0"
                           @click="taskChange(scope.row.id,3)" size="small" type="warning">移除</el-button>
              </template>
            </el-table-column >
            <el-table-column label="操作" align="center" width="240px" v-if="buttonPermissions.isDelete" fixed="right">
              <template slot-scope="scope">
                <el-button @click="cloneData(scope.row)" size="small" >复制</el-button>
                <el-button @click="timingData(scope.row)" size="small" >详情</el-button>
                <el-button type="danger" v-if="buttonPermissions.isDelete"
                           @click="deleteTask(scope.row)" size="small" >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination background
                         layout="total,sizes,prev,pager,next"
                         @current-change="currentChange"
                         @size-change="sizeChange"
                         :page-sizes="pagination.pageSizes"
                         :page-size.sync="pagination.pageSize"
                         :total="pagination.total"
                         :current-page.sync="pagination.currentPage"
                         class="paging fr">
          </el-pagination>
        </el-card>
        <el-dialog v-dialogDrag :title="dialogTitle" :visible.sync="isShow" @close="closeDialog"
                   :modal-append-to-body="false" :close-on-click-modal="false"  width="800px">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :inline="true" label-width="300px">
            <el-form-item label="账号名称" prop="synchronize_account_id">
              <el-popover v-if="isUpdata"
                @show="originalShow"
                placement="bottom"
                width="100%"
                trigger="click">
                <el-table :data="original_dataTable" size="small" ref="originalTable" row-key="id"
                          highlight-current-row @current-change="originalHandleSelectionChange" style="font-size:16px">
                  <el-table-column label="账号名称" prop="company_name" align="center">
                    <template slot-scope="scope">
                      <span style="font-size: 14px;cursor: pointer">{{scope.row.company_name}}</span>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination background
                               layout="total,sizes,prev,pager,next"
                               @current-change="original_currentChange"
                               @size-change="original_sizeChange"
                               :page-sizes="original_pagination.pageSizes"
                               :page-size.sync="original_pagination.pageSize"
                               :total="original_pagination.total"
                               :current-page.sync="original_pagination.currentPage"
                               class="paging fr">
                </el-pagination>
                <el-button slot="reference" size="small">{{original_name}}</el-button>
              </el-popover>
              <el-button v-else size="small">{{original_name}}</el-button>
            </el-form-item>
            <el-form-item label="任务类型" prop="task_code">
              <el-select v-model="ruleForm.task_code" :disabled="!isUpdata" size="small" style="width:400px">
                <el-option v-for="(key,value) in taskList" :key="value" :value="key+'-'+value">{{key}}-{{value}}</el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="服务名称" prop="bean_name">
              <el-input v-model="ruleForm.bean_name" :readonly="!isUpdata" size="small" style="width:400px"></el-input>
            </el-form-item>
            <el-form-item label="方法名称" prop="method_name">
              <el-input v-model="ruleForm.method_name" :readonly="!isUpdata" size="small" style="width:400px"></el-input>
            </el-form-item>
            <el-form-item label="任务定时表达式" prop="cron">
              <el-input v-model="ruleForm.cron" :readonly="!isUpdata" size="small" style="width:400px"></el-input>
            </el-form-item>
            <el-form-item label="获取多长时间的数据（单位分钟）" prop="data_intervals">
              <el-input v-model.number="ruleForm.data_intervals" :readonly="!isUpdata" type="number" size="small" style="width:400px"></el-input>
            </el-form-item>
            <el-form-item label="当前时间往前推算多长时间（单位分钟）" prop="push_forward_time">
              <el-input v-model.number="ruleForm.push_forward_time" :readonly="!isUpdata" type="number" size="small" style="width:400px"></el-input>
            </el-form-item>
            <el-form-item label="数据分包条数" prop="data_sum">
              <el-input-number v-model="ruleForm.data_sum" :disabled="!isUpdata" size="small" :min="50" :step="50"></el-input-number>
            </el-form-item>
          </el-form>
          <span  v-if="!isUpdata" style="font-size: 12px;color:red;display: block;text-align:right">*只有状态为未启用时才可修改详细信息</span>
          <div slot="footer" class="dialog-footer">
            <el-button @click="isShow = false" size="small">取 消</el-button>
            <!--判断是否显示保存按钮：isAdd 判断为是否为修改页面 -->
<!--            保证is_use != 1时为移除状态时才能保存-->
            <el-button v-show="isUpdata"
              type="primary" @click="confirmDialog" size="small">保 存</el-button>
          </div>
        </el-dialog>
      </div>
    </page>
  </el-row>
</template>
<style lang="scss">
  .page-content {
    .tag-card{
      >.el-card__body{
        >.el-row{
          margin-bottom: 12px;
        }
      }
    }
    padding: 15px;
    .fr {
      float: right;
    }
    .el-table {
      margin-bottom: 10px;
    }
    .paging {
      margin: 15px;
      height: 28px;
    }
    .tag-search{
      width: 40%;
      display: inline-block;
    }
    .tag-search .search-input{
      width: 300px;
      display: inline-block;
    }
    .tag-search .tag-name{
      font-size: 14px;
    }

  }

  body{
    .el-message-box__wrapper{
      .shanchuClass{
        .el-message-box__content{
          .el-message-box__message{
            p{
              max-height: 200px;
              overflow-y: auto;
              width: 100%;
              word-break:break-all;
            }
          }
        }
      }
    }
  }
  .popover{
    display: block;
    .databtn{
      width: 150px;
      overflow: hidden;
      text-overflow: ellipsis
    }
  }
  .popover-ul{
    max-height: 500px;
    overflow: auto;
    li{
      display: block;
      padding: 10px 20px
    }
  }

</style>
<script>
  let moment = require("moment");
  import page from "@/components/page/page";
  import pageheader from "@/components/page/pageheader";
  import Cascader from "@/components/sys/assembly/elcascader";
  export default {
    data() {
      let validateRegExp = (rule, value, callback)=>{
        if (value === '') {
          return callback(new Error('请输入时间'));
        }else{
          let regExp = /^[0-9]\d*$/
          if(!regExp.test(value)){
            return callback(new Error('请输入正整数，单位为分钟'));
          }
        }
        callback();
      };
      return {
        dataTable:[],
        keywords:'',
        status:'-1',
        pagination:{
          total:0,//总条目数
          currentPage:1,//当前页数
          pageSize:10,//每页显示条目个数
          pageSizes:[10,20,50,100],//每页显示个数选择器的选项设置
        },//表格分页参数
        dialogTitle:'添加定时任务',//模态框名称
        isShow:false,//是否显示模态框
        isAdd:false,//是否是新增模态框
        original_pagination:{
          total:0,//总条目数
          currentPage:1,//当前页数
          pageSize:10,//每页显示条目个数
          pageSizes:[10,20,50,100],//每页显示个数选择器的选项设置
        },//表格分页参数
        ruleForm:{
          synchronize_account_id:'',
          task_code:'',
          bean_name:'',
          method_name:'',
          cron:'',
          data_intervals:'',
          push_forward_time:'',
          data_sum:100
        },
        rules:{
          synchronize_account_id:[{required: true,message: "请选择账号名称", trigger: "blur"}],
          task_code:[{required: true,message: "请选择任务类型", trigger: "blur"}],
          bean_name:[{required: true,message: "请输入服务名称", trigger: "blur"}],
          method_name:[{required: true,message: "请输入方法名称", trigger: "blur"}],
          cron:[{required: true,message: "请输入任务定时表达式", trigger: "blur"}],
          data_intervals:[{required: true,validator:validateRegExp, trigger: "blur"}],
          push_forward_time:[{required: true,validator:validateRegExp, trigger: "blur"}],
          data_sum:[{required: true,message: "请输入数据分包条数", trigger: "blur"}],
        },
        taskList:{},//任务标记
        original_dataTable:[],//项目名称列表
        original_name:'选择账号',//项目名称
        isUpdata:false,//模态框是否允许填写,保存
        original_row:null,//当前显示的账号名称id

        buttonPermissions:{
          isAll:false,
          isUnmounted:false,
          isDelete:false,
          isHide:false,
        },
      }
    },
    inject: ["reload"],
    components: {
      page,
      pageheader,
      Cascader,//级联选择器组件
    },
    created() {
      this.getTaskList();
      this.getTaskCode()
      if (sessionStorage.buttonPermissions) {
        this.configPermissions(JSON.parse(sessionStorage.buttonPermissions))
      }
    },
    mounted() {
      //点击新增按钮
      this.$Bus.$on("taskAdd",() => {
        this.isAdd=true;
        this.dialogTitle='新增任务';
        this.isShow=true;
        this.isUpdata = true
      });
    },
    beforeDestroy(){
      this.$Bus.$off('taskAdd')
    },
    methods: {
      //配置按钮权限，根据权限不同调整表头渲染参数
      configPermissions(val){
        let buttonPermissions = val
        let menuButtonPermissions = [];//按钮权限数组
        buttonPermissions.forEach(e =>{
          for(let key in e){
            if(key == 'menu_code'){
              menuButtonPermissions.push(e[key])
            }
          }
        });
        this.buttonPermissions.isAll = menuButtonPermissions.includes('isAll') ? true : false;
        this.buttonPermissions.isUnmounted = menuButtonPermissions.includes('isUnmounted') ? true : false;
        this.buttonPermissions.isDelete = menuButtonPermissions.includes('isDevDelete') ? true : false;//删除
      },
      //表格序号显示方法
      indexMethod(index){
        return index + ((this.pagination.currentPage - 1) * this.pagination.pageSize) + 1
      },
      //获取任务列表
      getTaskList(keywords = '',page='1',page_size='10'){
        this.dataTable = []
        this.$Bus.$emit('Loading',true);
        let url = '/operating/permanent/task/list?keywords='+ encodeURIComponent(keywords) + '&page='+ page +
          '&page_size=' + page_size + '&status='+ this.status
        this.$api.get(url)
        .then(data => {
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false);
            return
          }
          //判断接口返回正常
          if(data.data){
            let _data = data.data
             console.log(_data,'数据');
            this.dataTable = _data.dataList ? _data.dataList.map(x=>{
              x.created_time = x.created_time ? moment(x.created_time).format("YYYY-MM-DD HH:mm") : ''
              x.updated_time = x.updated_time ? moment(x.updated_time).format("YYYY-MM-DD HH:mm") : ''
              return x
            }) : [];
            this.pagination.total = _data.dataCount;
            this.pagination.currentPage = _data.pageCode;
            this.pagination.pageSize = _data.pageSize;
          }
          this.$Bus.$emit('Loading',false)
        })
        .catch(err=>{
           console.log(err);
          this.$Bus.$emit('Loading',false)
        })
      },
      //每页显示条目个数change事件
      sizeChange(val){
        this.$Bus.$emit('Loading',true)
        this.getTaskList(this.keywords,this.pagination.currentPage,val)
      },
      //分页change事件
      currentChange(val){
        this.$Bus.$emit('Loading',true)
        this.getTaskList(this.keywords,val,this.pagination.pageSize)
      },
      //搜索按钮点击事件
      deviceSearch() {
        this.$Bus.$emit('Loading',true)
        this.pagination.currentPage = 1
        this.getTaskList(this.keywords,this.pagination.currentPage,this.pagination.pageSize)
      },
      //条件改变
      isChangeType(){
        this.pagination.currentPage = 1
        this.getTaskList(this.keywords,this.pagination.currentPage,this.pagination.pageSize)
      },
      //删除
      deleteTask(data){
        this.$confirm("是否删除服务‘"+ data.bean_name+"’？", "提示",{
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center:true
        })
        .then(() => {
          this.$Bus.$emit('Loading',true)
          this.delData(data.id);
        })
        .catch(() => {
          return
        });
      },
      delData(id){
        let url='/operating/permanent/task/delete-job?id='+ id
        this.$api.delete(url)
        .then(data=>{
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false);
            return
          }
          this.$Bus.$emit('Loading', true);
          this.getTaskList();
          this.$message({
            message: "删除成功",
            type: "success"
          });
          this.$Bus.$emit('Loading', false);
        })
        .catch(err=>{
          this.$Bus.$emit('Loading',false);
          console.log('错误');
        })
      },
      //查看详情
      timingData(data){
        console.log(data);
        this.isShow = true;
        this.isAdd = false;
        this.original_row = data.synchronize_account_id
        this.isUpdata = data.status == 0 ? true : false
        this.getTiming(data.id)
        this.getSynchronizeAccount(data.synchronize_account_id)
      },
      //复制该条数据
      cloneData(data){
        this.isShow = true;
        this.isAdd = true;
        this.original_row = data.synchronize_account_id
        this.isUpdata = true
        this.getTiming(data.id)
        this.getSynchronizeAccount(data.synchronize_account_id)
      },
      //根据id获取每条
      getTiming(id){
        let url = '/operating/permanent/task/get?id='+ id
        this.$api.get(url)
        .then(data=>{
          console.log(data);
          this.ruleForm = Object.assign({},data.data)
          this.ruleForm.task_code = this.ruleForm.task_desc + '-' + this.ruleForm.task_code
          this.$Bus.$emit("Loading", false);
        })
        .catch(err=>{
          console.log(err);
          this.$Bus.$emit("Loading", false);
        })
      },
      //根据id获取服务名称
      getSynchronizeAccount(id){
        let url = '/syn/synchronize/account/get-synchronize?id='+ id
        this.$api.get(url)
        .then(data=>{
          console.log(data);
          this.original_name = data.data.company_name
          this.$Bus.$emit("Loading", false);
        })
        .catch(err=>{
          console.log(err);
          this.$Bus.$emit("Loading", false);
        })
      },
      //启动，暂停，移除相互切换事件
      taskChange(id,n){
        this.$Bus.$emit("Loading", true);
        let url = ''
        if(n == 1){
          url = '/operating/permanent/task/start-job?id='+ id
        }else if(n == 2){
          url = '/operating/permanent/task/pause-job?id='+ id
        }else if(n == 3){
          url = '/operating/permanent/task/remove-job?id='+ id
        }
        this.$api.get(url)
        .then(data=>{
          console.log(data);
          this.getTaskList(this.keywords,this.pagination.currentPage,this.pagination.pageSize)
          this.$Bus.$emit("Loading", false);
        })
        .catch(err=>{
          console.log(err);
          this.$Bus.$emit("Loading", false);
        })
      },
      //选中企业数据展示
      originalShow(){
        this.getOriginalList(this.original_pagination.currentPage,this.original_pagination.pageSize)
      },
      //获取原始数据列表
      getOriginalList(pageCode = 1,page_size = 10){
        this.$Bus.$emit("Loading", true);
        let url = '/syn/synchronize/account/list?page='+ pageCode + '&page_size=' + page_size
        this.$api.get(url)
        .then(data=>{
          if(data){
            let _data = data.data
            this.original_dataTable = _data.dataList
            console.log(this.original_dataTable,'original_dataTable');
            this.original_pagination.total = _data.dataCount;
            this.original_pagination.currentPage = _data.pageCode;
            this.original_pagination.pageSize = _data.pageSize;
            console.log(this.original_row,'original_row');
            if(this.original_row){
              console.log('有id并赋值');
              for(let i in this.original_dataTable){
                if(this.original_dataTable[i].id == this.original_row){
                  this.$refs.originalTable.setCurrentRow(this.original_dataTable[i]);
                }
              }

            }
          }
          this.$Bus.$emit("Loading", false);
        })
        .catch(err=>{
          console.log(err);
          this.$Bus.$emit("Loading", false);
        })
      },
      //获取任务标记
      getTaskCode(){
        let url = '/syn/task/record/find-task-code'
        this.$api.get(url)
        .then(data=>{
          console.log(data);
          this.taskList = data.data;
          this.$Bus.$emit("Loading", false);
        })
        .catch(err=>{
           console.log(err);
          this.taskList = [];
          this.$Bus.$emit("Loading", false);
        })
      },
      original_sizeChange(val){
        this.getOriginalList(this.original_pagination.currentPage,val)
      },
      //分页change事件
      original_currentChange(val){
        this.getOriginalList(val,this.original_pagination.pageSize)
      },
      //表格单选操作
      originalHandleSelectionChange(data){
        if(data){
          this.ruleForm.synchronize_account_id = data.id;
          this.original_name = data.company_name;
        }
      },
      //调用启用接口
      setUse(id){
        let url = '/operating/permanent/task/use-job?id='+ id
        this.$api.get(url)
        .then(data=>{
          this.getTaskList(this.keywords,this.pagination.currentPage,this.pagination.pageSize)
          this.$Bus.$emit('Loading',false);
        })
        .catch(err=>{
          console.log(err);
          this.$Bus.$emit('Loading',false);
        })
      },
      //模态框保存按钮
      confirmDialog(){
        let dataV = {};
        let model = null;
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            this.$Bus.$emit('Loading',true);
            model = this.$refs.ruleForm.model;
            dataV.synchronize_account_id = model.synchronize_account_id
            dataV.task_desc = model.task_code.split('-')[0]
            dataV.task_code = model.task_code.split('-')[1]
            dataV.bean_name = model.bean_name
            dataV.method_name = model.method_name
            dataV.cron = model.cron
            dataV.data_intervals = model.data_intervals
            dataV.push_forward_time = model.push_forward_time
            dataV.data_sum = model.data_sum
            if(this.isAdd){
              this.confirmAdd(dataV);
            }else{
              dataV.id = this.ruleForm.id
              this.confirmUpdata(dataV);
            }

          } else {
            console.log("error submit!!");
            this.$Bus.$emit('Loading',false);
            return false;
          }
        });
      },
      //新增
      confirmAdd(dataV){
        let url='/operating/permanent/task/create';
        this.$api.post(url,dataV)
        .then(data=>{
          this.getTaskList(this.keywords, this.pagination.currentPage, this.pagination.pageSize)
          this.isShow = false
          this.$message({
            message: "添加成功",
            type: "success"
          });
          this.$Bus.$emit('Loading',false);
        })
        .catch(err=>{
          this.$Bus.$emit('Loading',false);
          console.log(err);
        })
      },
      //修改
      confirmUpdata(dataV){
        let url='/operating/permanent/task/update';
        this.$api.put(url,dataV)
        .then(data=>{
          this.getTaskList(this.keywords, this.pagination.currentPage, this.pagination.pageSize)
          this.isShow = false
          this.$message({
            message: "修改成功",
            type: "success"
          });
          this.$Bus.$emit('Loading',false);
        })
        .catch(err=>{
          this.$Bus.$emit('Loading',false);
          console.log(err);
        })
      },
      //关闭模态框
      closeDialog(){
        this.ruleForm.id = '';
        this.ruleForm.synchronize_account_id = '';
        this.ruleForm.is_use = '';
        this.original_name = '选择账号';
        this.original_row = '';
        this.$refs.ruleForm.resetFields();
        this.isUpdata = false
      },
    },
    watch: {}
  }
</script>
